//
//  YYDisplayView.m
//  DrawDemo
//
//  Created by 姚英 on 16/6/8.
//  Copyright © 2016年 Passion. All rights reserved.
//

#import "YYDisplayView.h"
#import "YYNumberLabel.h"

@interface YYDisplayView ()

@end

@implementation YYDisplayView

+ (instancetype)displayViewWithFrame:(CGRect)frame{
    
    YYDisplayView *view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] lastObject];

    view.frame = frame;
    
    return view;
}

-(void)awakeFromNib{
    
}

/// 数字动画
- (void)setNumber:(NSInteger)value oldNumber:(NSInteger)oldValue duration:(CFTimeInterval)duration{
    
    // 每次数字的变化数
    NSInteger  temp;
    CGFloat count;
    
    //除0 判断
    temp = ABS(value - oldValue);

    if (temp == 0) {
        return;
    }
    // 变化间隔
    NSTimeInterval interval = duration / temp; //Adjust for different animation speed
    if (interval <= 0.02) {
        interval = 0.02;
        count = ABS(value - oldValue) / (duration / interval);
        
    }else{
        count = 1;
    }
    
    NSTimeInterval delay = 0.0;
    
    if (oldValue <= value) {
        
                // 没有这个 -1 将会发生死循环,这个for永远不会结束,因为下面有个判断.
        for (CGFloat i = oldValue; i <= (value + count - 1); i+= count ) {
            // 超过value 就等于value
            if (i > value) {
                i = value;
            }

            NSString *labelText = [NSString stringWithFormat:@"%li", (long)(i+0.5)];
            [_numberLabel performSelector:@selector(setText:) withObject:labelText afterDelay:delay];
            delay += interval;
        }
    }
    else{
                // 没有这个 +1 将会发生死循环,这个for永远不会结束,因为下面有个判断.
        for (CGFloat i = oldValue; i >= (value - count + 1); i-= count) {
            if (i < value) {
                i = value;
            }
            NSString *labelText = [NSString stringWithFormat:@"%li", (long)(i+0.5)];
            [_numberLabel performSelector:@selector(setText:) withObject:labelText afterDelay:delay];
            delay += interval;
        }
    }
//    self.numberLabel.text = [NSString stringWithFormat:@"%li",value];
}

@end
